package com.k7.mobile.platform.bo.impl.nocache;

import net.spy.memcached.MemcachedClient;
import net.spy.memcached.internal.OperationFuture;

import com.k7.mobile.platform.bo.IMemCacheBO;
import com.k7.mobile.platform.bo.impl.BaseBOImpl;
import com.k7.mobile.platform.exception.BOException;

public class MemCacheBOImpl extends BaseBOImpl implements IMemCacheBO{

	private boolean enableCache;
		
	private MemcachedClient  memcachedClient;
	
	
	@Override
	public void set(String key, Object value, int expiredTime){

		try{
			memcachedClient.set(key, expiredTime, value);
		}catch(Exception e){
			log.error("JedisBOImpl:set,存储对象到redis失败.", e);
			throw new BOException("存储对象到redis失败.", e);
		}
	}
	
	@Override
	public <T> T get(String key){
		if(!enableCache)
			return null;

		try{
			Object b = memcachedClient.get(key);
			return (T) b;
		}catch(Exception e){
			log.error("JedisBOImpl:set,从redis获取对象失败.", e);
			throw new BOException("从redis获取对象失败.", e);
		}
	}
	
	@Override
	public boolean delete(String key){

		try{
			OperationFuture<Boolean> count = memcachedClient.delete(key);
			return count.get();
		}catch(Exception e){
			log.error("JedisBOImpl:set,redis计数失败.", e);
			throw new BOException("redis计数失败.", e);
		}
	}
	
	@Override
	public Long incr(String key){
		try{
			return memcachedClient.incr(key,1);
		}catch(Exception e){
			log.error("JedisBOImpl:incr,redis计数失败.", e);
			throw new BOException("redis计数失败.", e);
		}
	}
	
	

	public void setEnableCache(boolean enableCache) {
		this.enableCache = enableCache;
	}

	public void setMemcachedClient(MemcachedClient memcachedClient) {
		this.memcachedClient = memcachedClient;
	}

	
	
}
